package com.sakura.filter;

import com.alibaba.fastjson.JSON;
import com.sakura.common.BaseContext;
import com.sakura.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebFilter("/*")
@Slf4j
public class CheckLoginFilter implements Filter {
    // String[] urls={
    //         "/backend/**",
    //         "/front/**",
    //         "/employee/login",
    // };

    @Value("${filter.urls}")
    private String[] urls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 定义哪些资源需要拦截
        String requestURI = request.getRequestURI();
        boolean flag = checkUrl(urls,requestURI);
        if (flag){
            // 正常访问资源放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        // 判断后台是否登录
        Long userId = (Long)request.getSession().getAttribute("userInfo");
        if(userId != null){
            // 传入ID到线程局部变量,然后到元数据中取出
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        // 判断前台是否登录
        Long frontUserInfo = (Long)request.getSession().getAttribute("frontUserInfo");
        if(frontUserInfo != null){
            // 传入ID到线程局部变量,然后到元数据中取出
            BaseContext.setCurrentId(frontUserInfo);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        // 未登录响应json格式数据
        // 访问非法路径返回错误
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    private boolean checkUrl(String[] urls, String requestURI) {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if(match) return true;
        }
        return false;
    }

    @Override
    public void destroy() {
    }
}
